package com.plian.system.mybatis.search;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.TokenUtil;
import com.plian.spring.SpringUtil;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.mybatis.base.BaseEntity;
import com.plian.system.mybatis.support.Query;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.sys.orgzation.IOrgService;

import java.util.List;

/**
 *
 * @param <T>
 */
public class TokenSearch<T extends BaseEntity> {

    /**
     * 根据flag 判断是否过滤登录信息 1本级所有数据和下级通过审批数据 2本级所有数据
     *
     * @param wrapper
     * @param query
     * @return
     */
    public void addTokenQuery(QueryWrapper<T> wrapper, Query query){
        String orgId = TokenUtil.getTokenOrgId();
        if (query!= null && query.getFlag() != null && query.getFlag() == 1){
            IOrgService orgService = SpringUtil.getBean(IOrgService.class);
            GzwProperties gzwProperties = SpringUtil.getBean(GzwProperties.class);
            String gzwOrgId = gzwProperties.getId();
            if (orgId.equals(gzwOrgId)){
                //国资节点
                wrapper.lambda().and(andWrapper ->
                        andWrapper.eq(T::getStatus, FormStatusConstant.FINISH).or()
                                .eq(T::getCreateCompanyId, orgId)
                );
                return;
            }
            List<String> allChildIds = orgService.getAllChildIds(orgId);
            wrapper.lambda().and(andWrapper ->
                    andWrapper.in(T::getCreateCompanyId, allChildIds)
                            .eq(T::getStatus, FormStatusConstant.FINISH).or()
                            .eq(T::getCreateCompanyId, orgId)
            );
            return;
        }
        wrapper.lambda().eq(T::getCreateCompanyId, orgId);
    }

    /**
     * 没有流程的模块 根据flag 判断是否过滤登录信息 1本级所有数据和下级通过审批数据 2本级所有数据
     *
     * @param wrapper
     * @param query
     * @return
     */
    public void addTokenNoFlowQuery(QueryWrapper<T> wrapper, Query query){
        String orgId = TokenUtil.getTokenOrgId();
        if (query!= null && query.getFlag() != null && query.getFlag() == 1){
            IOrgService orgService = SpringUtil.getBean(IOrgService.class);
            GzwProperties gzwProperties = SpringUtil.getBean(GzwProperties.class);
            String gzwOrgId = gzwProperties.getId();
            if (orgId.equals(gzwOrgId)){
                //国资节点
                return;
            }
            List<String> allChildIds = orgService.getAllChildIds(orgId);
            wrapper.lambda().and(andWrapper ->
                    andWrapper.in(T::getCreateCompanyId, allChildIds)
            );
            return;
        }
        wrapper.lambda().eq(T::getCreateCompanyId, orgId);
    }
}
